﻿using ActionSystem.Core.ComboLogic;
using ActionSystem.Core.Ranges;
using ActionSystem.Core.Utils;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace ActionSystem.Core.ComboLogic
{
    [PoolInitAttribute(typeof(GameObjectPool<RectRangeBoxItem>), 50)]
    public class RectRangeBoxItem : RangeBoxItem2D
    {        
        protected override void PutBackToPool()
        {
            if(!IsDeleted)
            {
                GameObjectPool<RectRangeBoxItem>.Delete(this);
            }            
        }

        public override void SetRangeShape(IItem item)
        {
            base.SetRangeShape(item);
            RectItem r = item as RectItem;
            if (r != null)
            {
                var box = hitBox as BoxCollider2D;
                if(box != null)
                {
                    box.transform.rotation = Quaternion.Euler(r.rotation);
                    box.transform.position = new Vector2(r.offset.x, r.offset.y);
                    box.offset = Vector2.zero;
                    box.size = r.size;
                }
            }
        }

        public override Collider2D InitCollider()
        {
            return gameObject.AddComponent<BoxCollider2D>();
        }
        public override int HitDetect(int unityLayerMask)
        {
            if (value == null || unityLayerMask == 0)
            {
                return 0;
            }
            RectItem box = value as RectItem;
            if (box == null)
            {
                return 0;
            }
#if UNITY_EDITOR
            var defaultColor = XMLib.DrawUtility.D.color;
            XMLib.DrawUtility.D.color = Color.yellow;
            XMLib.DrawUtility.D.duration = 1/60f;
            var m3 = transform.localToWorldMatrix;
            XMLib.DrawUtility.D.DrawRect(box.size, m3);
            XMLib.DrawUtility.D.color = defaultColor;
#endif
            int count = Physics2D.OverlapBoxNonAlloc(transform.position, box.size,transform.rotation.eulerAngles.z,hitColiderRes, unityLayerMask);
            for (int i = 0; i < count; i++)
            {
                hitColiderRes[i].TryGetComponent<RangeBoxItem2D>(out hitRes[i]);
            }
            return count;
        }
    }
}


